package com.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.ListDataModel;

import org.apache.log4j.Logger;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.springframework.web.jsf.FacesContextUtils;

import com.builder.ClienteBuilder;
import com.dao.BaseModelDAO;
import com.model.Cliente;
import com.query.ClienteQuery;
import com.util.JSFUtil;
import com.util.ValidatorUtil;
import com.view.ContactoView;
import com.view.ClienteView;

@ManagedBean
@ViewScoped
@SuppressWarnings("serial")
public class ClienteController extends PaginableController<Cliente> {

	private Logger log = Logger.getLogger(ClienteController.class);
	private BaseModelDAO<Cliente> dao;
	private Cliente model;
	private ClienteQuery query;

	@ManagedProperty("#{clienteView}")
	private ClienteView view;

	@ManagedProperty("#{contactoController}")
	private ContactoController contactoController;

	@ManagedProperty("#{clienteBuilder}")
	private ClienteBuilder builder;

	@ManagedProperty("#{direccionController}")
	private DireccionController direccionController;

	@SuppressWarnings("unchecked")
	public ClienteController() {

		try {
			dao = (BaseModelDAO<Cliente>) FacesContextUtils
					.getWebApplicationContext(FacesContext.getCurrentInstance())
					.getBean("clienteDAO");
			query = new ClienteQuery();
			addEdit = false;

		} catch (Throwable e) {
			log.error("Error al inicializar la clase ClienteController", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}
	}

	public ClienteQuery getQuery() {
		return query;
	}

	public void setQuery(ClienteQuery query) {
		this.query = query;
	}

	public Cliente getModel() {
		return model;
	}

	public void setModel(Cliente model) {
		this.model = model;
	}

	public ClienteView getView() {
		return view;
	}

	public void setView(ClienteView view) {
		this.view = view;
	}

	public ClienteBuilder getBuilder() {
		return builder;
	}

	public void setBuilder(ClienteBuilder builder) {
		this.builder = builder;
	}

	public ContactoController getContactoController() {
		return contactoController;
	}

	public void setContactoController(ContactoController contactoController) {
		this.contactoController = contactoController;
	}

	public DireccionController getDireccionController() {
		return direccionController;
	}

	public void setDireccionController(DireccionController direccionController) {
		this.direccionController = direccionController;
	}

	@Override
	public void query(ActionEvent event) {
		loadList();
	}

	@Override
	public void edit(ActionEvent event) {

		try {
			model = lazyDM.getRowData();
			model = dao.findFULL(model.getID());
			view = builder.toView(model);
			contactoController.setListaContactos(view.getListaContactos());
			contactoController.setContactoDM(new ListDataModel<ContactoView>(
					view.getListaContactos()));
			direccionController.setDireccionView(view.getDireccion());
			addEdit = true;
		} catch (Throwable e) {
			log.error("Error al editar", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}

	}

	@Override
	public void delete(ActionEvent event) {

		try {
			model = lazyDM.getRowData();
			dao.delete(model);
			loadList();
		} catch (Throwable e) {
			log.error("Error al eliminar", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}
	}

	@Override
	public void add(ActionEvent event) {
		clear();
		addEdit = true;
		clear();
	}

	@Override
	public void save(ActionEvent event) {

		try {
			view.setListaContactos(contactoController.getListaContactos());
			view.setDireccion(direccionController.getDireccionView());

			List<String> errores = new ValidatorUtil().validate(view);

			if (errores.size() == 0) {

				model = builder.toDomain(view);

				if (model.getID() != null) {
					dao.edit(model);
					addEdit = false;
				} else {
					dao.save(model);
				}
				clear();
				JSFUtil.saveMessage("Elemento guardado con exito",
						FacesMessage.SEVERITY_INFO);
				if (!addEdit) {
					loadList();
				}
			} else {
				JSFUtil.saveMessages(errores);
			}
		} catch (Throwable e) {
			log.error("Error al guardar", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}
	}

	@Override
	public void cancel(ActionEvent event) {
		addEdit = false;
		lazyDM = null;
		clear();
	}

	@Override
	public void clear() {
		view = new ClienteView();
		model = new Cliente();
		contactoController.setView(new ContactoView());
		contactoController.setContactoDM(new ListDataModel<ContactoView>());
		direccionController.clear();
		contactoController.clear();
	}

	private void loadList() {

		lazyDM = new LazyDataModel<Cliente>() {
			@Override
			public List<Cliente> load(int first, int pageSize,
					String sortField, SortOrder sortOrder,
					Map<String, Object> filters) {

				Map<String, Object> filtro = new HashMap<String, Object>();
				filtro.put("nombre", query.getNombre());
				filtro.put("nombreFantasia", query.getNombreFantasia());

				return dao.getList(first, pageSize, "nombre", true, filtro,
						true);
			}
		};

		Map<String, Object> filtro = new HashMap<String, Object>();
		filtro.put("nombre", query.getNombre());
		filtro.put("nombreFantasia", query.getNombreFantasia());
		lazyDM.setRowCount(dao.count(filtro, true).intValue());
	}

}
